import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 配置axios基础路径（根据实际后端地址修改）
axios.defaults.baseURL = 'http://localhost:8088'

// 消息类型定义
interface Message {
  id: number
  content: string
  role: 'user' | 'assistant'
  created_at: string
}

// 会话类型定义
interface Conversation {
  id: number
  title: string
  updated_at: string
}

export const useChatStore = defineStore('chat', () => {
  // 状态
  const messages = ref<Message[]>([])
  const conversations = ref<Conversation[]>([])
  const currentConversationId = ref<number | null>(null)
  const selectedModel = ref<'deepseek' | 'kimi'>('deepseek')
  const isLoading = ref(false)

  // 计算属性（对应原getters）
  const hasMessages = computed(() => messages.value.length > 0)

  // 创建新会话
  const startNewChat = async (title?: string) => {
    try {
      // 这里简化处理，实际应从用户存储中获取user_id
      const userId = 1 // 需替换为实际登录用户ID

      const response = await axios.post('/conversations', { title }, {
        params: { user_id: userId }
      })

      currentConversationId.value = response.data.conversation_id
      messages.value = []
      loadConversations(userId) // 刷新会话列表
      return response.data.conversation_id
    } catch (error) {
      ElMessage.error('创建会话失败，请重试')
      console.error('创建会话错误:', error)
    }
  }

  // 发送消息
  const sendMessage = async (content: string) => {
    if (!currentConversationId.value) {
      // 如果没有当前会话，自动创建一个
      const convId = await startNewChat()
      if (!convId) return
    }

    isLoading.value = true
    try {
      const response = await axios.post('/chat', {
        conversation_id: currentConversationId.value,
        message: content
      })

      // 更新消息列表
      messages.value.push({
        id: Date.now(), // 临时ID，实际以接口返回为准
        content: content,
        role: 'user',
        created_at: new Date().toISOString()
      })

      // 添加助手回复
      messages.value.push({
        id: Date.now() + 1, // 临时ID
        content: response.data.assistant_message,
        role: 'assistant',
        created_at: new Date().toISOString()
      })

      return response.data
    } catch (error) {
      ElMessage.error('发送消息失败，请重试')
      console.error('发送消息错误:', error)
    } finally {
      isLoading.value = false
    }
  }

  // 加载用户会话列表
  const loadConversations = async (userId: number) => {
    try {
      const response = await axios.get('/conversations', {
        params: { user_id: userId }
      })
      conversations.value = response.data
    } catch (error) {
      ElMessage.error('加载会话列表失败')
      console.error('加载会话列表错误:', error)
    }
  }

  // 加载特定会话的消息
  const loadConversationMessages = async (conversationId: number) => {
    try {
      currentConversationId.value = conversationId
      const response = await axios.get(`/conversations/${conversationId}/messages`)

      // 转换后端返回的role格式（后端是enum，前端是字符串）
      messages.value = response.data.map((msg: any) => ({
        ...msg,
        role: msg.role.toLowerCase() as 'user' | 'assistant'
      }))
    } catch (error) {
      ElMessage.error('加载会话消息失败')
      console.error('加载会话消息错误:', error)
    }
  }

  // 切换模型
  const switchModel = async (modelName: 'deepseek' | 'kimi') => {
    try {
      // 转换为后端期望的模型名称格式
      const backendModelName = modelName === 'kimi' ? 'Moonshot' : 'Deepseek'
      await axios.post('/switch-model', { model_name: backendModelName })
      selectedModel.value = modelName
      ElMessage.success(`已切换到${modelName === 'kimi' ? 'Kimi' : 'Deepseek'}模型`)
    } catch (error) {
      ElMessage.error('切换模型失败')
      console.error('切换模型错误:', error)
    }
  }

  // 返回状态、计算属性和方法
  return {
    messages,
    conversations,
    currentConversationId,
    selectedModel,
    isLoading,
    hasMessages,
    startNewChat,
    sendMessage,
    loadConversations,
    loadConversationMessages,
    switchModel
  }
})